<template>
  <div class="app-container">
    <el-tabs type="card" @tab-click="handleClick" v-model="activeName">
      <el-tab-pane label="任务地图" name="first">
        <!-- <Index v-if="completeRefreshAssess"
                   :allListData="allListData"
                   :isSaveMapPolygon="isSaveMapPolygon"
                   :districtTreeList="districtTreeList"
                   @xzqhSelect="xzqhSelect"
                   @mapNewTask="mapNewTask"
                   @mapUpdTask="mapUpdTask"
                   @mapDelTask="mapDelTask"
                   @mapLoading="mapLoading"
                   @mapShowTask="mapShowTask"
        ></Index> -->
        <Map
          :districtTreeList="districtTreeList"
          :mutifileShpList="mutifileShpList"
          :addLayerData="addLayerData"
          :allListData="allListData"
          :layerStyle="layerStyle"
          :clearTaskLayer="clearTaskLayer"
          @mapNewTask="mapNewTask"
          @mapUpdTask="mapUpdTask"
          @mapDelTask="mapDelTask"
          @xzqhSelect="xzqhSelect"
          @uploadShp="uploadShp"
          @mapLoading="mapLoading"
          @isDataLayer="isDataLayer"
          @queryTaskRegionNameCodeListByGeomText="queryTaskRegionNameCodeListByGeomText"
          :taskRegionResultNameCodeList="taskRegionResultNameCodeList"
        ></Map>
        <!-- <p>任务地图</p>
        <p @click="areaSelect">行政区域选择区域</p> -->
      </el-tab-pane>
      <el-tab-pane label="任务列表" name="second">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px">
          <el-form-item label="任务编号" prop="taskNum">
            <el-input placeholder="请输入任务编号" v-model="queryParams.taskNum" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="queryParams.taskName" placeholder="请输入任务名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="任务状态" prop="taskStatus">
            <el-select v-model="queryParams.taskStatus" placeholder="请选择状态" clearable @keyup.enter="handleQuery">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="省" prop="province">
            <el-select v-model="queryParams.province" placeholder="请选择省" @change="chooseProvince" clearable
              value-key="id">
              <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="市" prop="city">
            <el-select v-model="queryParams.city" placeholder="请选择市" @change="chooseCity" clearable value-key="id">
              <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区/县" prop="county">
            <el-select v-model="queryParams.county" placeholder="请选择县" @change="chooseCounty" clearable
              value-key="id">
              <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
          </el-col>
        </el-row>
        <!-- container表格区域 -->
        <el-table :data="listData" v-loading="loading" row-key="dtId" ref="tableRef" stripe
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
          <el-table-column label="任务编号" align="center" prop="taskNum" />
          <el-table-column label="任务名称" align="center" prop="taskName">
            <template #default="scope">
              <span @click="handleDetil(scope.row.dtId)" style="color: #409eff;cursor: pointer;">{{
                  scope.row.taskName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="评估人" align="center" prop="createUserName" />
          <el-table-column label="任务状态" align="center" prop="taskStatus">
           
          </el-table-column>
          <el-table-column label="灾害类型" align="center" prop="disasterType" />
          <el-table-column label="任务地区" align="center" prop="taskDistrict" show-overflow-tooltip/>
          
          <el-table-column label="操作" align="center" width="200px" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button type="text" v-if="scope.row.taskStatus=='进行中'||scope.row.taskStatus=='退回修改'"  @click="update(scope.row)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
          @pagination="getList" />
      </el-tab-pane>
    </el-tabs>
    <!--查看/修改任务的弹出框 -->
    <el-dialog v-model="openAdd" :title="title" width="800px" append-to-body>
      <p class="dialogTitle">{{title}}</p>
      <table class="addTask">
        <div v-if="title == '新建任务'">
          <el-form :model="queryParamsAdd" :rules="rules" ref="rulesFormAdd" :inline="true" label-width="140px">           
            <el-row>
            	<el-form-item>
	              <span class="label">任务编号：</span><span>{{ queryParamsAdd.taskNum }}</span>
	            </el-form-item>
            </el-row>
            <el-row>
            	<el-form-item label="任务名称：" prop="taskName" style="width:90%">
                <el-input placeholder="请输入任务名称" clearable v-model="queryParamsAdd.taskName" />
              </el-form-item>
            </el-row>
          </el-form>
        </div>
        <tr v-if="title == '修改任务'">         
          <td>
            <span class="label">任务编号：</span><span>{{ queryParamsAdd.taskNum }}</span>
          </td>
        </tr>
        <tr v-if="title == '修改任务'">
          <td colspan="2">
            <el-form :model="queryParamsAdd" :rules="rules" ref="rulesFormAdd" :inline="true" label-width="140px">
              <el-form-item label="任务名称：" prop="taskName" style="width: 90%">
                <el-input placeholder="请输入任务名称" clearable v-model="queryParamsAdd.taskName" />
              </el-form-item>
            </el-form>
          </td>
        </tr>
        <div v-if="title == '查看任务'">
          <el-form :model="queryParamsAdd" :rules="rules" ref="rulesFormAdd" :inline="true" label-width="140px">           
            <el-row>
            	<el-form-item>
	              <span class="label">任务编号：</span><span>{{ queryParamsAdd.taskNum }}</span>
	            </el-form-item>
            </el-row>
            <el-row>
            	<el-form-item label="任务名称：" prop="taskName" style="width:90%">
                <el-input placeholder="请输入任务名称" disabled v-model="queryParamsAdd.taskName" />
              </el-form-item>
            </el-row>
          </el-form>
        </div>
        <tr>
          <td colspan="2">
            <span class="label">面积（平方公里）：</span>
            <!-- <span>{{ queryParamsAdd.taskArea }}</span> -->
             <el-link type="primary" :underline="false" @click="selectFeatureAll">查看</el-link>
          </td>
        </tr>
        <!-- <tr>
          <td colspan="2">
            <span class="label">任务区域：</span><span class="init-taskDivSpan">{{ queryParamsAdd.taskRegion.substr(0,358) }}</span>
          </td>
        </tr> -->
        <tr>
          <td colspan="2">
            <span class="label">任务地区：</span>
            <span class="init-taskDivSpan" :title="taskDistrictTitle" v-if="title == '新建任务'">{{ taskDistrictName}}</span>
            <span class="init-taskDivSpan" v-else>{{
                queryParamsAdd.taskDistrict
            }}</span>
          </td>
        </tr>
        <!--<tr>
          <td colspan="2">
            <span class="label">承担小组：</span><span>{{ queryParamsAdd.groupName }}</span><el-button style="margin-left:20px" @click="fenPeiAdd">修改分配</el-button>
          </td>
        </tr>-->
       	<tr>
          <td colspan="2">
          	<el-form :model="queryParamsAdd" ref="disasterTypeQuery" :rules="rules"  :inline="true" label-width="140px">
              <el-form-item label="灾害类型：" prop="disasterType" style="width: 90%">
                <el-checkbox-group v-model="queryParamsAdd.disasterType" :disabled="title=='查看'">
						    <el-checkbox label="1" :disabled="dzhpIsEdit">地震滑坡</el-checkbox>
						    <el-checkbox label="2" :disabled="styhIsEdit">砂土液化</el-checkbox>
						    <el-checkbox label="3" :disabled="rtzxIsEdit">软土震陷</el-checkbox>
						  </el-checkbox-group>
              </el-form-item>
            </el-form>
            
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <span class="label">评估人：</span><span>{{ queryParamsAdd.createUserName }}</span>
          </td>
        </tr>
        <!-- <tr>
          <td colspan="2">
            <span class="label">任务状态：</span>
            <span v-if="queryParamsAdd.taskStatus=='1'">进行中</span>
            <span v-if="queryParamsAdd.taskStatus=='2'">审核中</span>
            <span v-if="queryParamsAdd.taskStatus=='3'">退回修改</span>
            <span v-if="queryParamsAdd.taskStatus=='4'">已完成</span>
          </td>
        </tr> -->
      </table>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="title == '修改任务'" type="primary" @click="updateSaveTask">保 存</el-button>
          <el-button v-if="title == '新建任务'" type="primary" @click="saveTask">保 存</el-button>
          <!-- <el-button @click="cancelAdd">取 消</el-button> -->

        </span>
      </template>
    </el-dialog>  
    <!--新建任务查看面积 -->
    <el-dialog v-model="openMJ" title="面积查看" width="500px" append-to-body>
      <el-table id="tab" :data="tableData" style="text-align: center">
        <el-table-column prop="tdaName" label="区域" />
        <el-table-column prop="tdaArea" label="面积（平方公里）" />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="exportExcel('tab')">导 出</el-button>
        </span>
      </template>
    </el-dialog>
    <!--判断新建区域是否相交页面 -->
    <el-dialog v-model="isIntersectOpen" title="新建任务是否存在相交区域" width="500px" append-to-body>
      <div style="margin: 10px;font-size: 16px;color: darkgoldenrod;">新建任务中，存在相交区域，请删除相交区域重新新建任务！</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isIntersectOpen = false">取 消</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 行政区域选择 -->
		<div class="areaDialog" v-show="openArea">
			<div class="close">
				<el-icon>
					<Close @click="closeSelect" />
				</el-icon>
			</div>
			<el-form :model="form" :rules="rules" ref="rulesForm" label-width="100px">
				<el-form-item label="选择地区" prop="taskDistrict" style="width:280px">
					<el-cascader v-model="form.taskDistrict" placeholder="请选择地区" :props="{ multiple: true }" clearable separator="," collapse-tags collapse-tags-tooltip @change="getCheckedArea" ref="checkedAreaRef" :options="optionsSelect">
					</el-cascader>
				</el-form-item>
			</el-form>
			<el-button @click="add()" type="primary" style="margin:20px 0">新建任务</el-button>
		</div> 
    <!-- 数据图层显示 -->
    <div class="dataLayer" v-show="openLayer">
			<!-- <el-tabs v-model="activeNameLayer" class="demo-tabs" @tab-click="handleClickLayer">
      <el-tab-pane label="国家级数据" name="first"> -->
        <el-tree :data="dataLayer" :props="defaultProps" show-checkbox @check-change="handleNodeClick" />
      <!-- </el-tab-pane>
      <el-tab-pane label="省级数据" name="second">
        <el-tree :data="dataLayer" :props="defaultProps" show-checkbox @check-change="handleNodeClick" />
      </el-tab-pane>
    </el-tabs> -->
		</div> 
    <div class="uploadDialog" v-show="openUpload">
      <div class="close">
				<el-icon>
					<Close @click="closeUploadShp" />
				</el-icon>
			</div>
      <el-upload
        v-model:file-list="fileList"
        class="upload-demo"
        :action="uploadFileUrl"
        :before-remove="beforeRemove"
        :limit="limit"
        :on-exceed="handleExceed"
        :on-progress="handSuccess"
      >
        
        <template #trigger>
          <el-button type="primary">请选择文件</el-button>
        </template>
        <template #default>
          <el-button type="primary" style="margin-left: 10px" @click="saveUploadShp">确定</el-button>
        </template>
        <template #tip>
          <div class="el-upload__tip">
            只支持.shp文件格式!
          </div>
        </template>
      </el-upload>
    </div>
  </div>
</template>
<script setup name="assess">
//地图
import Map from '@/map/taskManage/map.vue';
import FileSaver from "file-saver";
import * as XLSX from "xlsx";
//地图空间分析
//import {getSubTaskRegionIntersection} from "@/map/taskmanage/sceneexamine/mapUtil.js";
import { getProvince, getChildArea } from "@/api/system/division";
import userStore from '@/store/modules/user'
import { getProvinces, getYear, getDistrict } from "@/utils/group.js";
import { open } from 'shapefile'
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/attachment/uploadFile"); // 上传的图片服务器地址
import {
  getTask,
  delTask,
  updateTask,
  addSubTask,
  addTask,
  detailTask,
  viewTaskArea,
  addListTask,
  getAllTaskList,
  getTaskBian
} from "@/api/taskmanage/task";
import {getAreaTree,getDistrictBoundary} from "@/api/taskmanage/sceneExame";
import { queryProvinceCityCountyNameCodeListByGeomText } from "@/api/taskmanage/taskRegionQuery";
import {  getUserId } from "@/utils/auth";
import { iServerHttp } from "@/map/projMap.js"

const { proxy } = getCurrentInstance();
const taskDistrictName = ref("");
const taskDistrictTitle = ref("");
const checkedAreaRef = ref();
// const props = { multiple: true };
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const fileList = ref([])
const dzhpIsEdit = ref(false);
const styhIsEdit = ref(false);
const rtzxIsEdit = ref(false);
const userName = computed(() => userStore().name)
const options = [
  
  {
    value: "1",
    label: "进行中",
  },
  {
    value: "2",
    label: "审核中",
  },
  {
    value: "3",
    label: "退回修改",
  },
  {
    value: "4",
    label: "已完成",
  },
];
const newYear = getYear();
const optionsYear = [
  {
    value: String(newYear),
    label: String(newYear),
    id: 1,
  },
  {
    value: String(newYear + 1),
    label: String(newYear + 1),
    id: 2,
  },
  {
    value: String(newYear + 2),
    label: String(newYear + 2),
    id: 3,
  },
];
const loading = ref(true);
const loading1 = ref(true);
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
const openFp = ref(false);
const taskID = ref('')
const fpId = ref({
  id: undefined,
  parentId: undefined,
  taskName: undefined,
  createUser:undefined
});
const openAdd = ref(false);
const openMJ = ref(false)
const openAddSub = ref(false);
const openArea = ref(false);
const openLayer = ref(false)
const openUpload = ref(false)
const layerStyle = ref(true)
const title = ref("");
const titleSub = ref("");
const activeName = ref("first");
const activeNameLayer = ref("first")
const queryGroupObj = ref(undefined);
const openDetail = ref(false);
const total = ref(0);
const num = ref();
const addLayerData = ref({})
const parentTaskCode = ref();
const parentTaskYear = ref();
const parentTaskId = ref();
const numAdd = ref(2);
const districtListName = ref("");
const delFlag = ref(false);
const rules = reactive({
  taskDistrict: [{ required: true, message: "请选择地区", trigger: "change" }],
  taskYear: [{ required: true, message: "请选择年份", trigger: "change" }],
  taskName: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
  disasterType: [{ required: true, message: "请选择灾害类型", trigger: "change" }],
});
const rules2 = reactive({
  taskName: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
  subdistrictList: [
    { required: true, message: "请输入选择省份", trigger: "blur" },
  ],
});
let detilList = reactive({
  preAssessTaskEntity: {
    taskYear: undefined,
    taskNum: undefined,
    taskName: undefined,
    taskArea: undefined,
    taskRegion: undefined,
    districtList: undefined,
    groupName: undefined,
    groupLeader: undefined,
    taskDistrict: undefined,
  },
  expertlist: undefined,
  memberlist: "",
});
const props = defineProps({
  // 图片数量限制
  limit: {
    type: Number,
    default: 1,
  },
})
const data = reactive({
  form: {
    taskDistrict: "",
  },
  selectProvince: [],
  listData: [],
  tableData: [],
  dataLayer: [
    // {id: 1,label: '高程数据'},
    // {id: 2,label: '坡度数据'},
    // {id: 3,label: '坡向数据'},
    // {id: 4,label: '活断层'},
    // {id: 5,label: '道路数据'},
    // {id: 6,label: '水系数据'},
    // {id: 7,label: '地层岩性数据'},
    // {id: 8,label: '地震动峰值加速度'},
    /*{id: 9,label: '地貌数据', name: '地貌数据', radioLabel: 'dm', code: 'dm', table:"dzzh_sys_landform",url:iServerHttp()+"/iserver/services/map-fxfzdzzh/rest/maps/dzzh_sys_landform@fxfzdzzh",zIndex:6,fieldId:"dsl_id"},
    {id: 10,label: '天然密度数据', name: '天然密度数据', radioLabel: 'trmd', code: 'trmd', table:"dzzh_sys_natural_density",url:iServerHttp()+"/iserver/services/map-fxfzdzzh/rest/maps/dzzh_sys_natural_density@fxfzdzzh",zIndex:6,fieldId:"dsn_id"},*/

    {id: "",label: '地貌数据', name: '地貌数据', radioLabel: 'dm', code: 'dm', table:"dzzh_sys_landform",url:iServerHttp()+"/iserver/services/map-dzzhTifFile/rest/maps/坡度_1700548615544",zIndex:6,fieldId:"dsl_id"},
    {id: "",label: '天然密度数据', name: '天然密度数据', radioLabel: 'trmd', code: 'trmd', table:"dzzh_sys_natural_density",url:iServerHttp()+"/iserver/services/map-dzzhTifFile/rest/maps/坡向_1717641364729",zIndex:6,fieldId:"dsn_id"},
  ],
  queryParams: {
    page: 1,
    rows: 10,
    taskNum: "",
    taskName: "",
    taskStatus: "",
    province: "",
    city: "",
    county: "",
  },
  queryParamsAdd: {
    taskYear: "",
    taskNum: "",
    taskName: "",
    taskArea: "",
    taskRegion: "",
    parentdistrictList: [],
    taskDistrict: "",
    groupName: "",
    groupLeader: "",
    groupId: "",
    groupLeaderId: "",
    regionCodes:""//地图行政区划code,code字符串
  },
  queryParamsSubAdd: {
    taskYear: "",
    taskNum: "",
    taskName: "",
    taskArea: "",
    taskRegion: "",
    subdistrictList: "",
    taskDistrict: "",
    groupName: "",
    groupLeader: "",
    groupLeaderId: "",
    groupId: "",
    regionCodes:""//地图行政区划code,code字符串
  },
  subTaskData: [],
  subDataPage: {
    page: 1,
    rows: 10,
  },
  optionsSelect: [],
  selectArea: [],
});

let {
  form,
  queryParams,
  listData,
  queryParamsAdd,
  queryParamsSubAdd,
  selectArea,
  tableData,
  subTaskData,
  optionsSelect,
  dataLayer,
} = toRefs(data);

//地图传参--start
const completeRefreshAssess = ref(false);//防止刷新后地图不显示
const allListData = ref([]);
const mutifileShpList = ref([])
const isSaveMapPolygon = ref(false);//判断是否完成保存任务区域
const xzqhSelect = ()=>{//行政区划选择区域
  openUpload.value = false
  areaSelect();
}
const isDataLayer = (flag)=>{
  selectDataLayer(flag)
}

const uploadShp = ()=>{// shp文件上传
  openArea.value = false
  openUploadShpTool()
}
//地图圈选查询行政区划结果列表
  const taskRegionResultNameCodeList = ref([]);
  //根据地图圈选区域，查询行政区划--省|市|区县的名称和code列表
  function queryTaskRegionNameCodeListByGeomText(geomText) {
    console.log("查询行政区划名称和code列表"+geomText);
    queryProvinceCityCountyNameCodeListByGeomText(geomText).then((response) => {
      nextTick(() => {
        console.log("查询行政区划名称和code列表result:");
        console.log(response.data);
        taskRegionResultNameCodeList.value = response.data;
      });
    });
  }
const isIntersectOpen = ref(false)
const mapNewTask = (temp)=>{//新建任务
  console.log('新建任务参数')
	console.log(temp)
  if(temp == true) {
    isIntersectOpen.value = true
    openAdd.value = false;
  }else{
    isIntersectOpen.value = false
    isSaveMapPolygon.value = false;//判断是否完成保存任务区域
    getTaskNum();
    subTaskData.value = [];
    title.value = "新建任务";
    num.value = 0;
    openAdd.value = true;
    resetAdd();
    // queryParamsAdd.value.taskArea = temp.taskArea;
    tableData.value = temp.polygonList
    console.log(tableData.value)
    queryParamsAdd.value.taskRegion = temp.taskRegion;
    let arrayString = ''
    if(temp.parentdistrictList != undefined) {
      arrayString = temp.parentdistrictList.toString()
    }
    queryParamsAdd.value.parentdistrictList = arrayString;
    queryParamsAdd.value.createUserName = userName.value
    queryParamsAdd.value.regionCodes = "";//地图行政区划code,code字符串
    temp.arrayList.forEach(item =>{
      if(item != undefined) {
        arrayString += item.join(',') + ',';
      }
    })
    taskDistrictTitle.value = arrayString
    taskDistrictName.value = arrayString
    if(arrayString.length>100) {
      taskDistrictName.value = arrayString.substring(0,100) + '...';
    }else{
      taskDistrictName.value = arrayString;
    }
    
    districtListName.value = getMapProvinces(taskDistrictName.value);
  }
}
const mapUpdTask = (row)=>{//修改任务
  updateParentHandle(row);
}
const mapDelTask = (row)=>{//删除任务
  delSubTask(row);
}

const mapLoading = (msg)=>{//地图查询loading
  if(msg!=null){
    proxy.$modal.loading(msg);
  }else{
    proxy.$modal.closeLoading();
  }
}
const mapShowTask = (id)=>{//查看任务
  handleDetil(id);
}

function handleNodeClick (row,flag){
  let params = {
    data: row,
    layerState: flag
  }
  addLayerData.value = params
}
function beforeRemove(file, fileList) {
  fileList.value = fileList;
}
//上传文件时
function handSuccess(event, file, fList) {
  let type = file.name.split('.')[1]
  if (type != 'shp') {
    // fileList.value = fList.filter(item => item.name != file.name)
    fileList.value = []
    proxy.$modal.msgError(`请选择.shp格式文件!`);
  }
}
// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}
//处理地图圈选省份
function getMapProvinces(taskDistrict){
  const str = taskDistrict.replace(/-/g, ",")
  const arr =  [...new Set(str.split(","))]
  let newArr = []
  arr.forEach(item=>{
    if(item.indexOf('省')!=-1){
      newArr.push(item)
    }else if (item=='北京市'||item == '天津市'||item=='上海市'||item=='重庆市'||item=='内蒙古自治区'||item=='内蒙古自治区'||item=='广西壮族自治区'||item=='西藏自治区'||item=='宁夏回族自治区'||item=='新疆维吾尔自治区'||item=='香港特别行政区'||item=='澳门特别行政区') {
      newArr.push(item)
    }
  })
  let brr =[]
  brr =  newArr.map(
      (item, index) => {
        return Object.assign({}, { value: item, label: item, id: index + 1 });
      }
  );
  return brr
}
// 删除任务
function delSubTask(row) {
  proxy.$modal
    .confirm("确认删除该任务？")
    .then(function () {
      return delTask([row.dtId]);
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
      getList();
    })
    .catch(() => { });
}
// 修改任务
function updateParentHandle(row) {
  title.value = "修改任务";
  num.value = 0;
  detailTask({ dtId: row.dtId }).then((response) => {
    queryParamsAdd.value = response.data;
    if(response.data.disasterType!=[]||response.data.disasterType!=null){
    	queryParamsAdd.value.disasterType = response.data.disasterType.split(",");
    }else{
    	queryParamsAdd.value.disasterType = [];
    }
    openAdd.value = true;
  });
  viewTaskArea({ dtId: row.dtId }).then(response => {
    tableData.value = response.data
  })
}
//获取行政区划总面积
function getAllSelectArea(array){
  let areaCount = 0;
  console.log(array.length);
  if(array!=null && array.length>0){
    for(let i=0;i<array.length;i++){
      let name = array[i];
      let arr = name.split('-');
      console.log(name+","+arr.length);
      if(arr.length==1){//省
        let province = arr[0];
        let areaTemp = getAreaByAllName("1",province,null,null);//根据行政区划全称获取省市区面积信息
        console.log("areaTemp"+areaTemp);
        areaCount += areaTemp;
        console.log("areaCount"+areaCount);
      }else if(arr.length==2){//市或直辖市的区县
        let province = arr[0];
        let city = arr[1];
        let areaTemp = getAreaByAllName("2",province,city,null);//根据行政区划全称获取省市区面积信息
        console.log("areaTemp"+areaTemp);
        areaCount += areaTemp;
        console.log("areaCount"+areaCount);
      }else if(arr.length==3){//区县
        let province = arr[0];
        let city = arr[1];
        let area = arr[2];
        let areaTemp = getAreaByAllName("3",province,city,area);//根据行政区划全称获取省市区面积信息
        console.log("areaTemp"+areaTemp);
        areaCount += areaTemp;
        console.log("areaCount"+areaCount);
      }
    }
  }
  if(areaCount>0){
    areaCount = areaCount.toFixed(3);//四舍五入保留3位小数
  }

  return areaCount;
}
function saveUploadShp() {
  if (fileList.value.length != 0) {
    if(fileList.value.length == 1){
      let arrayList = []
      const reader = new FileReader()
      let fileData = fileList._rawValue[0].raw
      reader.readAsArrayBuffer(fileData)
      reader.onload = function (e) {
        open(this.result).then(source => source.read().then(function log(result) {
          if (result.done) {
            mutifileShpList.value = arrayList
            return
          }
          arrayList.push(result.value)
          return source.read().then(log)
        })).catch(
          error => console.error(error.stack)
        )
      }
    } else{
      let arrayList = []
      for(let i=0;i<fileList.value.length;i++){
        const reader = new FileReader()
        let fileData = fileList._rawValue[i].raw
        reader.readAsArrayBuffer(fileData)
        reader.onload = function (e) {
          open(this.result)
            .then(source => source.read()
              .then(function log(result) {
                if (result.done) return
                arrayList.push(result.value)
                if (i == fileList.value.length - 1) {
                  mutifileShpList.value = arrayList
                }
                return source.read().then(log)
              }))
            .catch(error => console.error(error.stack))
        }
      }
    }
    closeUploadShp()
  } else{
    proxy.$modal.msgError(`请上传.shp文件`);
  }
}
function getAreaByAllName(type,province,city,area){//根据行政区划全称获取省市区面积信息
  //type:0省 | 1市 | 2区县
  let areaCount = 0;
  let districtTreeDataList = districtTreeList.value;
  if(districtTreeDataList!=null && districtTreeDataList!=""){
    //获取行政区划树列表
    let treeList = districtTreeDataList;
    if(treeList!=null && treeList.length>0){
      for(let i=0;i<treeList.length;i++){
        let provinceData = treeList[i];//省节点
        if(provinceData!=null){
          let provinceName = provinceData.name;//省
          if(type=="1" && province==provinceName){
            let cityList = provinceData.children;//市列表
            if(cityList!=null){
              for(let j=0;j<cityList.length;j++){
                let cityData = cityList[j];
                if(cityData!=null){
                  let areaList = cityData.children;//区县列表
                  if(areaList!=null && areaList.length>0){
                    for(let j=0;j<areaList.length;j++){
                      let areaData = areaList[j];
                      if(areaData!=null){
                        areaCount += areaData.area / 1000000;//平方公里
                      }
                    }
                  }else{//直辖市
                    areaCount += cityData.area / 1000000;//平方公里
                  }
                }
              }
            }
            return areaCount;
          }
          let cityList = provinceData.children;//市列表
          if(cityList!=null){
            for(let j=0;j<cityList.length;j++){
              let cityData = cityList[j];
              if(cityData!=null){
                let cityName = cityData.name;//市
                if(type=="2" && city==cityName){
                  let areaList = cityData.children;//区县列表
                  if(areaList.length>0){
                    for(let j=0;j<areaList.length;j++){
                      let areaData = areaList[j];
                      if(areaData!=null){
                        areaCount += areaData.area / 1000000;//平方公里
                      }
                    }
                  }else{//直辖市的区县
                    areaCount = cityData.area / 1000000;//平方公里
                  }
                  return areaCount;
                }
                let areaList = cityData.children;//区县列表
                if(areaList!=null){
                  for(let j=0;j<areaList.length;j++){
                    let areaData = areaList[j];
                    if(areaData!=null){
                      let areaName = areaData.name;//区县
                      if(type=="3" && area==areaName){
                        areaCount += areaData.area / 1000000;//平方公里
                        return areaCount;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  return areaCount;
}
//查询行政区划树列表
const districtTreeList = ref([]);
const districtBoundaryList = ref([]);//行政区划经纬度信息
const districtCount = ref(0);//选择的行政区划数量
//查询行政区划经纬度信息
function getDistrictBoundaryByCode(codeList) {
  tableData.value = []
  let mjList = []
  let geomList = []
  for(let m=0;m<codeList.length;m++){
    let code = codeList[m];
    //查询行政区划经纬度信息
    console.log("查询行政区划经纬度信息"+code);
    getDistrictBoundary(code).then((response) => {
      nextTick(() => {
        console.log("查询行政区划经纬度信息result:");
        console.log(response.data);
        let area = getAllSelectArea([queryParamsAdd.value.parentdistrictList[m]]);
        queryParamsAdd.value.taskArea = area.toString();
        queryParamsAdd.value.createUserName = userName.value
        mjList.push(
          {
            tdaArea: area.toString(),
            tdaName: response.data.name,
          }
        )
        if(m == codeList.length - 1) {
          tableData.value = mjList
        }
        //截取数据防止报错--仅用于展示不保存
        let subStr = response.data.coordinate;
        subStr = subStr.substring(0,1000);
        districtBoundaryList.value.push(subStr);
        if(districtCount.value==districtBoundaryList.value.length){//判断是否全部查询完毕
          let region = "";
          let list = districtBoundaryList.value;
          for(let i=0;i<list.length;i++){
            if(i>0){
              region += ";";
            }
            region += list[i];
          }
          console.log("全部查询完毕--行政区划经纬度信息");
          // queryParamsAdd.value.taskRegion = region;
          // queryParamsAdd.value.taskRegion = response.data.coordinate;
          queryParamsAdd.value.taskRegion = '';
          //地图获取行政区划总面积
          //新建任务
          proxy.$refs["rulesForm"].validate((vaild) => {
            if (!vaild) {
              return;
            }
            getTaskNum();
            subTaskData.value = [];
            title.value = "新建任务";
            num.value = 0;
            openAdd.value = true;
            proxy.$modal.closeLoading();
          });
        }
      });
    });
  }
}
//根据所有省市县全名字符串获取codelist
function getCodeByAllName(allName){
  let allCodeList = [];
  if(allName!=null && allName!=""){
    let array = allName.split("、");
    //获取行政区划树列表
    let treeList = districtTreeList.value;
    for(let i=0;i<array.length;i++){
      let name = array[i];
      let code = null;
      let arr = name.split('-');
      if(arr.length==1){//省或直辖市
        if(treeList!=null && treeList.length>0){
          for(let i=0;i<treeList.length;i++){
            let provinceData = treeList[i];//省节点
            if(provinceData!=null){
              let provinceName = provinceData.name;//省
              if(name==provinceName){
                let provinceCode = provinceData.code;//省编码
                code = provinceCode;
                break;
              }
            }
          }
        }
      }else if(arr.length==2){//市或直辖市的区县
        if(treeList!=null && treeList.length>0){
          for(let i=0;i<treeList.length;i++){
            let provinceData = treeList[i];//省节点
            if(provinceData!=null){
              let provinceName = provinceData.name;//省
              if(arr[0]==provinceName){
                let bool = false;
                let cityList = provinceData.children;//市列表
                if(cityList!=null){
                  for(let j=0;j<cityList.length;j++){
                    let cityData = cityList[j];
                    if(cityData!=null){
                      let cityName = cityData.name;//市
                      if(arr[1]==cityName){
                        let cityCode = cityData.code;//市编码
                        code = cityCode;
                        bool = true;
                        break;
                      }
                    }
                  }
                }
                if(bool){
                  break;
                }
              }
            }
          }
        }
      }else if(arr.length==3){//区县
        if(treeList!=null && treeList.length>0){
          for(let i=0;i<treeList.length;i++){
            let provinceData = treeList[i];//省节点
            let bool = false;
            if(provinceData!=null){
              let provinceName = provinceData.name;//省
              if(arr[0]==provinceName){
                let cityList = provinceData.children;//市列表
                if(cityList!=null){
                  for(let j=0;j<cityList.length;j++){
                    let cityData = cityList[j];
                    if(cityData!=null){
                      let cityName = cityData.name;//市
                      if(arr[1]==cityName){
                        let areaList = cityData.children;//区县列表
                        if(areaList!=null){
                          for(let j=0;j<areaList.length;j++){
                            let areaData = areaList[j];
                            if(areaData!=null){
                              let areaName = areaData.name;//区县
                              if(arr[2]==areaName){
                                let areaCode = areaData.code;//区县编码
                                code = areaCode;
                                bool = true;
                                break;
                              }
                            }
                          }
                        }
                        if(bool){
                          break;
                        }
                      }
                    }
                  }
                }
              }
            }
            if(bool){
              break;
            }
          }
        }
      }
      //添加code
      allCodeList.push(code);
    }
  }

  return allCodeList;
}

//获取新建子任务地图区域信息
function getSubTaskMapRegion(type){
  //type:okSubAdd保存子任务|okSubAddNext保存并创建下一个子任务
  proxy.$modal.loading("正在保存，请稍候...");
  //地图获取行政区划总面积
  let area = getAllSelectArea([queryParamsSubAdd.value.subdistrictList]);
  queryParamsSubAdd.value.taskArea = area.toString();
  let provinceName = queryParamsSubAdd.value.subdistrictList;//省名
  //根据所有省市县全名字符串获取codelist
  let codeList = getCodeByAllName(provinceName);
  console.log("查询行政区划codeList"+codeList);
  //选择的行政区划数量
  districtCount.value = codeList.length;
  console.log("选择的行政区划数量"+districtCount.value);
  let regionCodes = "";
  for(let i=0;i<codeList.length;i++){
    let code = codeList[i];
    if(i>0){
      regionCodes += ",";
    }
    regionCodes += code;
  }
  districtBoundaryList.value = [];//清空行政区划经纬度
  if(queryParamsAdd.value.taskRegion.indexOf("MULTIPOLYGON")==-1) {//地图圈选父任务
    console.log("地图圈选父任务");
    queryParamsSubAdd.value.taskRegion = queryParamsAdd.value.taskRegion;
    queryParamsSubAdd.value.regionCodes = "";//清空
  }else{//行政区划选择父任务
    console.log("行政区划选择父任务");
    let parentRegionCodes = queryParamsAdd.value.regionCodes;
    console.log("父任务行政区划code"+parentRegionCodes+",子任务选择省份"+regionCodes);
    let tempCode = regionCodes.substring(0,2);//省份code保留2位
    console.log("tempCode:"+tempCode);
    let parentRegionCodeArray = parentRegionCodes.split(",");
    let childRegionCode = "";
    for(let i=0;i<parentRegionCodeArray.length;i++){
      let parentRegionCode = parentRegionCodeArray[i];
      if(parentRegionCode.indexOf(tempCode)==0){//省份相同2位
        if(childRegionCode!=""){
          childRegionCode += ",";
        }
        childRegionCode += parentRegionCode;
      }
    }
    console.log("子任务行政区划"+childRegionCode);
    queryParamsSubAdd.value.regionCodes = childRegionCode;//地图行政区划code,code字符串
    console.log("行政区划选择父任务");
  }
  console.log(queryParamsAdd.value);
  //查询子任务行政区划经纬度信息
  for(let m=0;m<codeList.length;m++){
    let code = codeList[m];
    //查询行政区划经纬度信息
    console.log("查询子任务行政区划经纬度信息"+code);
    getDistrictBoundary(code).then((response1) => {
      nextTick(() => {
        console.log("查询子任务行政区划经纬度信息result:");
        console.log(response1.data);
        districtBoundaryList.value.push(response1.data.coordinate);
        if(districtCount.value==districtBoundaryList.value.length){//判断是否全部查询完毕
          let region = "";
          let list = districtBoundaryList.value;
          for(let i=0;i<list.length;i++){
            if(i>0){
              region += ";";
            }
            region += list[i];
          }
          console.log("全部查询完毕--子任务行政区划经纬度信息");
          if(queryParamsAdd.value.taskRegion.indexOf("MULTIPOLYGON")==-1) {//地图圈选父任务
            console.log("获取子任务区域经纬度（地图圈选父任务与省份的交集）");
            //获取子任务区域经纬度（地图圈选父任务与省份的交集）
            queryParamsSubAdd.value.taskRegion = getSubTaskRegionIntersection(queryParamsAdd.value.taskRegion,region);
          }else {//行政区划选择父任务
            //截取数据防止报错--仅用于展示不保存
            region = region.substring(0,10000);
            queryParamsSubAdd.value.taskRegion = region;
          }
          console.log(queryParamsSubAdd.value.subdistrictList);
          //queryParamsSubAdd.value.taskDistrict = queryParamsSubAdd.value.subdistrictList;//任务区域-省份
          console.log("子任务地图行政区划code,code字符串：");
          console.log(queryParamsSubAdd.value.regionCodes);
          proxy.$modal.closeLoading();
          if(type=="okSubAdd"){//
            proxy.$refs["rulesFormSubAdd"].validate((vaild) => {
              if (!vaild) {
                return;
              }
              if (queryGroupObj.value) {
                queryParamsSubAdd.value.groupName = queryGroupObj.value.groupName;
                queryParamsSubAdd.value.groupLeader = queryGroupObj.value.groupLeader;
                queryParamsSubAdd.value.groupId = queryGroupObj.value.id;
                queryParamsSubAdd.value.groupLeaderId = queryGroupObj.value.groupLeaderId;
              }
              console.log("输出任务地区：");
              console.log(queryParamsSubAdd.value.subdistrictList);
              // 新增
              if (titleSub.value == "新建子任务") {
                if (numAdd.value == 1) {
                  addSubTask({
                    ...queryParamsSubAdd.value,
                    subdistrictList: [queryParamsSubAdd.value.subdistrictList],
                    taskYear: parentTaskYear.value,
                    parentTask: parentTaskCode.value,
                    parentId: parentTaskId.value,
                    parentdistrictList:queryParamsAdd.value.parentdistrictList,
                  }).then((response) => {
                    openAddSub.value = false;
                    proxy.$modal.msgSuccess(response.data.message);
                    resetSubData();
                    getList();
                    queryGroupObj.value = undefined;
                    getSubList(parentTaskId.value);
                  });
                } else {
                  addTask({
                    parentTask: queryParamsAdd.value,
                    subTask: {
                      ...queryParamsSubAdd.value,
                      subdistrictList: [queryParamsSubAdd.value.subdistrictList],
                      taskYear: parentTaskYear.value,
                      parentTask: parentTaskCode.value,
                    },
                  }).then((response) => {
                    proxy.$modal.msgSuccess("保存成功");
                    numAdd.value = 1;
                    openAddSub.value = false;
                    resetSubData();
                    getSubList(response.data.parentTaskId);
                    queryGroupObj.value = undefined;
                    parentTaskId.value = response.data.parentTaskId;
                    //地图传参
                    isSaveMapPolygon.value = true;
                  });
                }
              }
            });
          }else if(type=="okSubAddNext"){//保存并创建下一个子任务
            proxy.$refs["rulesFormSubAdd"].validate((vaild) => {
              if (!vaild) {
                return;
              }
              // 新增
              if (queryGroupObj.value) {
                queryParamsSubAdd.value.groupName = queryGroupObj.value.groupName;
                queryParamsSubAdd.value.groupLeader = queryGroupObj.value.groupLeader;
                queryParamsSubAdd.value.groupId = queryGroupObj.value.id;
                queryParamsSubAdd.value.groupLeaderId = queryGroupObj.value.groupLeaderId;
              }
              if (numAdd.value == 1) {
                addSubTask({
                  ...queryParamsSubAdd.value,
                  subdistrictList: [queryParamsSubAdd.value.subdistrictList],
                  taskYear: parentTaskYear.value,
                  parentTask: parentTaskCode.value,
                  parentId: parentTaskId.value,
                  parentdistrictList:queryParamsAdd.value.parentdistrictList,
                }).then((response) => {
                  proxy.$modal.msgSuccess("保存成功");
                  getSubTaskNum(parentTaskCode.value);
                  resetSubData();
                  getList();
                  queryGroupObj.value = undefined;
                  getSubList(parentTaskId.value);
                });
              } else {
                addTask({
                  parentTask: queryParamsAdd.value,
                  subTask: {
                    ...queryParamsSubAdd.value,
                    subdistrictList: [queryParamsSubAdd.value.subdistrictList],
                    taskYear: parentTaskYear.value,
                    parentTask: parentTaskCode.value,
                  },
                }).then((response) => {
                  proxy.$modal.msgSuccess("保存成功");
                  numAdd.value = 1;
                  getSubTaskNum(parentTaskCode.value);
                  resetSubData();
                  // rulesFormSubAdd.value.clearValidate();
                  getSubList(response.data.parentTaskId);
                  queryGroupObj.value = undefined;
                  parentTaskId.value = response.data.parentTaskId;
                  //地图传参
                  isSaveMapPolygon.value = true;
                });
              }
            });
          }
        }
      });
    });
  }
}
//地图传参--end

/*切换标签页*/
function handleClick(tab, event) {
  if (tab.index == 1) {
    openArea.value = false;
    openUpload.value = false;
    if (openLayer.value == true) {
      layerStyle.value = false
    }
    openLayer.value = false;
    resetArea();
    getList();
  }else{
    layerStyle.value = true
    //隐藏地图
    completeRefreshAssess.value = false;
    //地图查询全部任务
    getAllList();
  }
}
function handleClickLayer(tab, event) {
  if(tab.index == 0) {
    dataLayer.value = [
      {id: 9,label: '地貌数据', name: '地貌数据', radioLabel: 'dm', code: 'dm', table:"dzzh_sys_landform",url:iServerHttp()+"/iserver/services/map-fxfzdzzh/rest/maps/dzzh_sys_landform@fxfzdzzh",zIndex:6,fieldId:"dsl_id"},
      {id: 10,label: '天然密度数据', name: '天然密度数据', radioLabel: 'trmd', code: 'trmd', table:"dzzh_sys_natural_density",url:iServerHttp()+"/iserver/services/map-fxfzdzzh/rest/maps/dzzh_sys_natural_density@fxfzdzzh",zIndex:6,fieldId:"dsn_id"},
    ]
  }else {
    dataLayer.value = [
      {id: 9,label: '地貌数据', name: '地貌数据', radioLabel: 'dm', code: 'dm', table:"dzzh_sys_landform",url:iServerHttp()+"/iserver/services/map-fxfzdzzh/rest/maps/dzzh_sys_landform@fxfzdzzh",zIndex:6,fieldId:"dsl_id"},
      {id: 10,label: '天然密度数据', name: '天然密度数据', radioLabel: 'trmd', code: 'trmd', table:"dzzh_sys_natural_density",url:iServerHttp()+"/iserver/services/map-fxfzdzzh/rest/maps/dzzh_sys_natural_density@fxfzdzzh",zIndex:6,fieldId:"dsn_id"},
    ]
  }
}
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.dtId);
	single.value = selection.length != 1;
  multiple.value = !selection.length;
//	selection.forEach((item) => {
//  if (item.taskStatus == "3" || item.taskStatus == "2") {
//    delFlag.value = false;
//  } else {
//    delFlag.value = true;
//  }
//	});
};

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  cityData.value = [];
  areaData.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 获取省列表 */
function getProvinceData() {
  getProvince().then((response) => {
    provinceData.value = response.data;
  });
}

function chooseProvince(value) {
  queryParams.value.city = null;
  queryParams.value.county = null;
  queryParams.value.province = value.name;
  cityData.value = [];
  areaData.value = [];
  getChildArea(value.id).then((response) => {
    cityData.value = response.data;
  });
  /*provinceData.value.map((item) => {
    //遍历数据
    if (item.id == value.id) {
      if (
        item.name == "北京市" ||
        item.name == "天津市" ||
        item.name == "上海市" ||
        item.name == "重庆市"
      ) {
        cityData.value.push(JSON.parse(JSON.stringify(item)));
      } else {
        getChildArea(value.id).then((response) => {
          cityData.value = response.data;
        });
      }
      return;
    }
  });*/
}
// 定义导出表格触发事件
function exportExcel(tabid) {
  const wb = XLSX.utils.table_to_book(document.querySelector('#' + tabid), {
    raw: true // 如果表格里有数字、日期这些、需要加上raw: true
  });
  /* 获取二进制字符串作为输出 */
  var wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: true,
    type: 'array'
  });
  try {
    FileSaver.saveAs(
      // Blob 对象表示一个不可变、原始数据的类文件对象
      new Blob([wbout], { type: 'application/octet-stream' }),
      // 设置导出文件名称
      "面积列表信息.xlsx"
    );
  } catch (e) {
    if (typeof console !== 'undefined') console.log(e, wbout);
  }
  return wbout;
}
function chooseCity(value) {
  queryParams.value.city = value.name;
  queryParams.value.county = null;
  areaData.value = [];
  getChildArea(value.id).then((response) => {
    areaData.value = response.data;
  });
}

function chooseCounty(value) {
  queryParams.value.county = value.name;
}

// 部门  树形数据
// 处理数据
function disposeata(data) {
  data.forEach((item) => {
    item.label = item.name;
    item.key = item.id;
    item.children && disposeata(item.children);
  });
  return data;
}
function getTreeselect() {
  getAreaTree().then((response) => {
    nextTick(() => {
      optionsSelect.value = disposeata(JSON.parse(response.data));
      console.log("行政区划列表");
      //地图行政区划列表
      districtTreeList.value = optionsSelect.value;
      console.log(districtTreeList.value);
    });
  });
}

function getCheckedArea() {
  let taskDistrict = checkedAreaRef.value.getCheckedNodes();
  taskDistrict = taskDistrict.filter(option => !(option.parent && option.parent.checked))
  queryParamsAdd.value.parentdistrictList = taskDistrict.map((item, index) => {
    return item.pathLabels.join("-");
  });
  var arr = JSON.parse(JSON.stringify(queryParamsAdd.value.parentdistrictList));
  queryParamsAdd.value.parentdistrictList = arr;
  taskDistrictName.value = getDistrict(arr);
  districtListName.value = getProvinces(taskDistrictName.value);
}

/** 获取列表操作 */
function getList() {
  if(activeName.value=="first"){
    //地图查询全部任务
    getAllList();
  }else{
    loading.value = true;
    getTask(queryParams.value).then((response) => {
      listData.value = response.data.rows;
      loading.value = false;
      total.value = response.data.total;
    });
  }
}

//地图查询全部任务
function getAllList() {
  loading.value = true;
  completeRefreshAssess.value = true;//防止地图刷新后不显示--
  //地图查询全部任务
  getAllTaskList().then((response) => {
    nextTick(() => {
      console.log("地图查询全部任务：");
      console.log(response.data);
      allListData.value = response.data;
      //completeRefreshAssess.value = true;//防止地图刷新后不显示--
      loading.value = false;
    });
  });
}


/** 删除按钮操作 */
function handleDelete() {
//if (delFlag.value) {
    proxy.$modal
      .confirm("删除任务将删除该任务关联的所有信息，请确认是否要删除？")
      .then(function () {
        return delTask(ids.value);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
        proxy.$refs['tableRef']?.clearSelection();
      })
      .catch(() => { });
//} else {
//  //proxy.$modal.msgWarning("审核、结束状态的任务不可删除");
//}
}

// 打开行政选区
function areaSelect() {
  openArea.value = true;
  resetArea();
}
function selectDataLayer(flag) {
  openLayer.value = flag
}
function openUploadShpTool() {
  openUpload.value = true
}
// 选择关闭后的回调
function closeSelect() {
  openArea.value = false;
  resetArea();
}
function closeDataLayer() {
  openLayer.value = false
}
function closeUploadShp() {
  openUpload.value = false
  fileList.value = []
}
function resetArea() {
  selectArea.value = [];
  proxy.resetForm("rulesForm");
}
// 新建任务
function add() {
  proxy.$modal.loading("正在查询，请稍候...");
  districtBoundaryList.value=[];//行政区划经纬度信息
  //查询行政区划经纬度信息
  console.log("查询行政区划经纬度信息");
  console.log(taskDistrictName.value);
  //地图获取行政区划总面积
  //let area = getAllSelectArea(queryParamsAdd.value.parentdistrictList);
  //queryParamsAdd.value.taskArea = area.toString();
  //根据所有省市县全名字符串获取codelist
  let codeList = getCodeByAllName(taskDistrictName.value);
  console.log("查询行政区划codeList");
  console.log(codeList);
  //选择的行政区划数量
  districtCount.value = codeList.length;
  console.log("选择的行政区划数量"+districtCount.value);
  let regionCodes = "";
  for(let i=0;i<codeList.length;i++){
    let code = codeList[i];
    if(i>0){
      regionCodes += ",";
    }
    regionCodes += code;
  }
  resetAdd();
  queryParamsAdd.value.regionCodes = regionCodes;//地图行政区划code,code字符串
  //查询行政区划经纬度信息
  getDistrictBoundaryByCode(codeList);
  /*//新建任务
  proxy.$refs["rulesForm"].validate((vaild) => {
    if (!vaild) {
      return;
    }
    //resetAdd();
    getTaskNum();
    subTaskData.value = [];
    title.value = "新建任务";
    num.value = 0;
    openAdd.value = true;
    //地图获取行政区划总面积
    let area = getAllSelectArea(queryParamsAdd.value.parentdistrictList);
    queryParamsAdd.value.taskArea = area.toString();
    proxy.$modal.closeLoading();
  });*/
}

// 新建子任务
function addSub(row) {
  numAdd.value = 1;
  resetSubData();
  getSubTaskNum(row.taskNum);
  parentTaskCode.value = row.taskNum;
  parentTaskYear.value = row.taskYear;
  parentTaskId.value = row.id;
  districtListName.value = getProvinces(row.taskDistrict);
  queryParamsAdd.value.parentdistrictList = row.taskDistrict.split('、');
  console.log("新建子任务row:");
  console.log(row);
  //任务区域
  queryParamsAdd.value.taskRegion = row.taskRegion;
  if(queryParamsAdd.value.taskRegion.indexOf("MULTIPOLYGON")==-1) {//地图绘制区域
    console.log("地图绘制区域");
  }else{
    console.log("行政区划选择区域");
    //根据所有省市县全名字符串获取codelist
    let codeList = getCodeByAllName(row.taskDistrict);
    console.log("查询行政区划codeList");
    console.log(codeList);
    //选择的行政区划数量
    districtCount.value = codeList.length;
    console.log("选择的行政区划数量"+districtCount.value);
    let regionCodes = "";
    for(let i=0;i<codeList.length;i++){
      let code = codeList[i];
      if(i>0){
        regionCodes += ",";
      }
      regionCodes += code;
    }
    //父任务行政区划code,code字符串
    queryParamsAdd.value.regionCodes = regionCodes;//地图行政区划code,code字符串
  }
  titleSub.value = "新建子任务";
  num.value = 2;
  openAddSub.value = true;
}

// 新建子任务
function addSub2(row) {
  proxy.$refs["rulesFormAdd"].validate(async(vaild) => {
    if (vaild) {
      // 表格表单验证
        resetSubData();
        getSubTaskNum(row.taskNum);
        titleSub.value = "新建子任务";
        num.value = 2;
        openAddSub.value = true;
        parentTaskCode.value = row.taskNum;
        parentTaskYear.value = row.taskYear;
    }
  });
}

/** 查看按钮操作 */
function handleDetil(id) {
	title.value = "查看任务";
  openAdd.value = true;
  dzhpIsEdit.value = true;
  styhIsEdit.value = true;
  rtzxIsEdit.value = true;
  detailTask({ dtId: id }).then((response) => {
    queryParamsAdd.value = response.data;
    if(response.data.disasterType!=""||response.data.disasterType!=null){
    	queryParamsAdd.value.disasterType = response.data.disasterType.split(",");
    }else{
    	queryParamsAdd.value.disasterType = [];
    }
  });
  viewTaskArea({ dtId: id }).then(response => {
    tableData.value = response.data
  })
}
//新建任务查看按钮
function selectFeatureAll() {
  openMJ.value = true
}
// 修改任务
function update(row) {
  title.value = "修改任务";
  dzhpIsEdit.value = false;
  styhIsEdit.value = false;
  rtzxIsEdit.value = false;
  taskID.value = row.dtId
  detailTask({ dtId: row.dtId }).then((response) => {
    queryParamsAdd.value = response.data;
    if(response.data.disasterType!=""||response.data.disasterType!=null){
    	queryParamsAdd.value.disasterType = response.data.disasterType.split(",");
    }else{
    	queryParamsAdd.value.disasterType = [];
    }
    openAdd.value = true;
  });
  viewTaskArea({ dtId: row.dtId }).then(response => {
    tableData.value = response.data
  })
}

// 改变年份
function changeYear(val){
  getTaskNum(val)
}
// 获取任务编码
function getTaskNum(taskYear) {
  getTaskBian({taskYear:taskYear}).then((response) => {
    nextTick(() => {
      queryParamsAdd.value.taskNum = response.data;
    });
  });
  return queryParamsAdd.value.taskNum;
}

// 获取子任务编码
function getSubTaskNum(taskNum) {
  getSubTaskBian({ taskNum: taskNum }).then((response) => {
    nextTick(() => {
      queryParamsSubAdd.value.taskNum = response.data;
    });
  });
  return queryParamsAdd.value.taskNum;
}

/** 提交按钮 */
function okAdd() {
  proxy.$refs["rulesFormAdd"].validate((vaild) => {
    if (!vaild) {
      return;
    }
    //截取数据防止报错--仅用于展示不保存
    let subStr = queryParamsAdd.value.taskRegion;
    subStr = subStr.substring(0,10000);
    queryParamsAdd.value.taskRegion = subStr;
    queryParamsAdd.value.disasterType = queryParamsAdd.value.disasterType.join(",");
    // 修改
    updateTask( queryParamsAdd.value ).then((response) => {
      openAdd.value = false;
      proxy.$modal.msgSuccess("修改成功");
      resetAdd();
      getList();
    });

  });
}
function resetAdd() {
  queryParamsAdd.value.taskNum = "";
  queryParamsAdd.value.taskName = "";
  queryParamsAdd.value.taskArea = "";
  queryParamsAdd.value.taskRegion = "";
  queryParamsAdd.value.taskDistrict = "";
  queryParamsAdd.value.disasterType = [];
  tableData.value = []
  proxy.resetForm("rulesFormAdd");
}
const clearTaskLayer = ref(false)
async function saveTask() {
  clearTaskLayer.value = false
  let taskEntity = {
    taskNum: queryParamsAdd.value.taskNum,
    taskName: queryParamsAdd.value.taskName,
    taskDistrict: queryParamsAdd.value.parentdistrictList.toString(),
    disasterType: queryParamsAdd.value.disasterType.length>0?queryParamsAdd.value.disasterType.join(''):"",
    taskRegion: queryParamsAdd.value.taskRegion,
    regionCodes: queryParamsAdd.value.regionCodes,
    createUserName: getUserId(),
  }
  const rulesFormAddValidate = await proxy.$refs['rulesFormAdd'].validate((valid, fields) => { valid, fields });
  const disasterTypeValidate = await proxy.$refs['disasterTypeQuery'].validate((valid, fields) => { valid, fields });
  if(rulesFormAddValidate&&disasterTypeValidate){
    addListTask({taskEntity: taskEntity,areaList: tableData.value}).then((response) => {
        proxy.$modal.msgSuccess("保存成功");
        clearTaskLayer.value = true
        cancelAdd();
        getAllList();
      });
  }
}
async function updateSaveTask() {
  let taskEntity = {
    dtId: taskID.value,
    taskName: queryParamsAdd.value.taskName,
    disasterType: queryParamsAdd.value.disasterType.length>0?queryParamsAdd.value.disasterType.join(''):"",
    updateUser: getUserId(),
  }
  const rulesFormAddValidate = await proxy.$refs['rulesFormAdd'].validate((valid, fields) => { valid, fields });
  const disasterTypeValidate = await proxy.$refs['disasterTypeQuery'].validate((valid, fields) => { valid, fields });
  if(rulesFormAddValidate&&disasterTypeValidate){
    updateTask(taskEntity).then(response =>{
        proxy.$modal.msgSuccess("修改成功");
        cancelAdd()
      })
  }
}
// 取消
function cancelAdd() {
  openAdd.value = false;
  resetAdd();
}

function closeAdd() {
  openAdd.value = false;
  resetAdd();
  openArea.value = false;
  resetArea();
}
/** 提交按钮 */
function okSubAdd() {
  // 新增
  if (titleSub.value == "新建子任务") {
    //获取新建子任务地图区域信息
    getSubTaskMapRegion("okSubAdd");
  } else {
    proxy.$refs["rulesFormSubAdd"].validate((vaild) => {
      if (!vaild) {
        return;
      }
      if (queryGroupObj.value) {
        queryParamsSubAdd.value.groupName = queryGroupObj.value.groupName;
        queryParamsSubAdd.value.groupLeader = queryGroupObj.value.groupLeader;
        queryParamsSubAdd.value.groupId = queryGroupObj.value.id;
        queryParamsSubAdd.value.groupLeaderId = queryGroupObj.value.groupLeaderId;
      }
      //截取数据防止报错--仅用于展示不保存
      let subStr = queryParamsSubAdd.value.taskRegion;
      subStr = subStr.substring(0,10000);
      queryParamsSubAdd.value.taskRegion = subStr;
      // 修改
      updateTask(queryParamsSubAdd.value).then((response) => {
        openAddSub.value = false;
        proxy.$modal.msgSuccess("修改成功");
        getSubList(parentTaskId.value);
        getList();
        resetSubData();
      });
    });
  }
  /* proxy.$refs["rulesFormSubAdd"].validate((vaild) => {
     if (!vaild) {
       return;
     }
     if (queryGroupObj.value) {
       queryParamsSubAdd.value.groupName = queryGroupObj.value.groupName;
       queryParamsSubAdd.value.groupLeader = queryGroupObj.value.groupLeader;
       queryParamsSubAdd.value.groupId = queryGroupObj.value.id;
       queryParamsSubAdd.value.groupLeaderId = queryGroupObj.value.groupLeaderId;
     }
     // 新增
     if (titleSub.value == "新建子任务") {
       if (numAdd.value == 1) {
         addSubTask({
           ...queryParamsSubAdd.value,
           subdistrictList: [queryParamsSubAdd.value.subdistrictList],
           taskYear: parentTaskYear.value,
           parentTask: parentTaskCode.value,
           parentId: parentTaskId.value,
           parentdistrictList:queryParamsAdd.value.parentdistrictList,
         }).then((response) => {
           openAddSub.value = false;
           proxy.$modal.msgSuccess(response.data.message);
           resetSubData();
           getList();
           queryGroupObj.value = undefined;
           getSubList(parentTaskId.value);
         });
       } else {
         addTask({
           parentTask: queryParamsAdd.value,
           subTask: {
             ...queryParamsSubAdd.value,
             subdistrictList: [queryParamsSubAdd.value.subdistrictList],
             taskYear: parentTaskYear.value,
             parentTask: parentTaskCode.value,
           },
         }).then((response) => {
           proxy.$modal.msgSuccess("保存成功");
           numAdd.value = 1;
           openAddSub.value = false;
           resetSubData();
           getSubList(response.data.parentTaskId);
           queryGroupObj.value = undefined;
           parentTaskId.value = response.data.parentTaskId;
           //地图传参
           isSaveMapPolygon.value = true;
         });
       }
     } else {
       // 修改
       updateTask(queryParamsSubAdd.value).then((response) => {
         openAddSub.value = false;
         proxy.$modal.msgSuccess("修改成功");
         getSubList(parentTaskId.value);
         getList();
         resetSubData();
       });
     }
   });*/
}

function okSubAddNext() {
  //获取新建子任务地图区域信息
  getSubTaskMapRegion("okSubAddNext");
  /*proxy.$refs["rulesFormSubAdd"].validate((vaild) => {
    if (!vaild) {
      return;
    }
    // 新增
    if (queryGroupObj.value) {
      queryParamsSubAdd.value.groupName = queryGroupObj.value.groupName;
      queryParamsSubAdd.value.groupLeader = queryGroupObj.value.groupLeader;
      queryParamsSubAdd.value.groupId = queryGroupObj.value.id;
      queryParamsSubAdd.value.groupLeaderId = queryGroupObj.value.groupLeaderId;
    }
    if (numAdd.value == 1) {
      addSubTask({
        ...queryParamsSubAdd.value,
        subdistrictList: [queryParamsSubAdd.value.subdistrictList],
        taskYear: parentTaskYear.value,
        parentTask: parentTaskCode.value,
        parentId: parentTaskId.value,
        parentdistrictList:queryParamsAdd.value.parentdistrictList,
      }).then((response) => {
        proxy.$modal.msgSuccess("保存成功");
        getSubTaskNum(parentTaskCode.value);
        resetSubData();
        getList();
        queryGroupObj.value = undefined;
        getSubList(parentTaskId.value);
      });
    } else {
      addTask({
        parentTask: queryParamsAdd.value,
        subTask: {
          ...queryParamsSubAdd.value,
          subdistrictList: [queryParamsSubAdd.value.subdistrictList],
          taskYear: parentTaskYear.value,
          parentTask: parentTaskCode.value,
        },
      }).then((response) => {
        proxy.$modal.msgSuccess("保存成功");
        numAdd.value = 1;
        getSubTaskNum(parentTaskCode.value);
        resetSubData();
        // rulesFormSubAdd.value.clearValidate();
        getSubList(response.data.parentTaskId);
        queryGroupObj.value = undefined;
        parentTaskId.value = response.data.parentTaskId;
        //地图传参
        isSaveMapPolygon.value = true;
      });
    }
  });*/
}
function resetSubData() {
  queryParamsSubAdd.value.taskYear = "";
  queryParamsSubAdd.value.taskNum = "";
  queryParamsSubAdd.value.taskName = "";
  queryParamsSubAdd.value.taskArea = "";
  queryParamsSubAdd.value.taskRegion = "";
  queryParamsSubAdd.value.subdistrictList = "";
  (queryParamsSubAdd.value.taskDistrict = ""),
    (queryParamsSubAdd.value.groupName = "");
  queryParamsSubAdd.value.groupLeader = "";
  queryParamsSubAdd.value.groupLeaderId = "";
  queryParamsSubAdd.value.groupId = "";
  proxy.resetForm("rulesFormSubAdd");
}
// 取消新建子任务
function cancelAddSub() {
  openAddSub.value = false;
  getSubList(parentTaskId.value);
}

getYear();
getList();
getProvinceData();
getTreeselect();
</script>
<style scoped lang="scss">
.area span.label {
  text-align: right;
  margin-right: 14px;
  display: inline-block;
  color: #606266;
  font-weight: 700;
  width: 30px;
}

.smallHeader {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #1890ff;
  position: relative;
  color: #fff;
  font-weight: 700;
}

.addTask,
.addSubTask {
  width: 700px;
  margin: 0 auto;

  td {
    width: 350px;
  }

  .label {
    text-align: right;
    display: inline-block;
    color: #606266;
    font-weight: 700;
    height: 32px;
    width: 142px;
    padding-right: 14px;
  }
}

h3 {
  color: #333;
  height: 21px;
  font-size: 16px;
  line-height: 21px;
  display: flex;
  align-items: center;
  margin-left: 40px;

  span {
    margin-right: 12px;
    display: inline-block;
    width: 3px;
    height: 16px;
    background: #333;
  }
}

.areaDialog {
  text-align: center;

  .close {
    text-align: right;

    .el-icon {
      color: #606266;
      padding: 20px 0;
      margin-right: 10px;
      right: 0px;
      font-size: 22px;
    }
  }
  width: 320px;
  position: absolute;
  top: 270px;
  left: 308px;
  background: rgba($color: #fff, $alpha: 0.9);
}
.dataLayer {
  height: 80px;
  text-align: center;
  // width: 320px;
  position: absolute;
  top: 400px;
  left: 120px;
  // background: #001b43;
  background-color:rgba(228, 232, 237, 0.6)!important;
  .el-tree {
    margin-top: 10px;
    background: none;
    color:#000;
  }
}
.uploadDialog {
  text-align: center;
  .close {
    text-align: right;

    .el-icon {
      color: #606266;
      padding: 20px 0;
      margin-right: 10px;
      right: 0px;
      font-size: 22px;
    }
  }
  width: 320px;
  position: absolute;
  top: 413px;
  left: 308px;
  background: rgba($color: #fff, $alpha: 0.9);
}
</style>
